package com.dx.as.upload;


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.json.JSONObject;

public class UploadUtil {
    /**
     *
     * @param urlPath
     *            map 参数 <参数名称 , 参数值>
     * @param fileParams
     *            map 文件类型 参数 <参数名称 , 文件路径>
     *
     */
    public static String postFile(String urlPath, Map<String, Object> mParams,
                                  Map<String, String> fileParams ,String imgPath) throws FileNotFoundException {
        String PREFIX = "--"; // 前缀
        String LINE_END = "\r"; // 换行
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识
        URL url;
        HttpURLConnection connection;
        try {
            url = new URL(urlPath);
            connection = (HttpURLConnection) url.openConnection();
            // 设置超时时间
            connection.setReadTimeout(30000);
            connection.setConnectTimeout(20000);
            // 请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            // 开启输入流
            connection.setDoInput(true);
            // 开启输出流
            connection.setDoOutput(true);
            // 关闭缓存
            connection.setUseCaches(false);
            // 设置编码
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("connection", "keep-alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 设置内容类型及定义BOUNDARY
            connection.setRequestProperty("Content-Type", "multipart/form-data"
                    + ";boundary=" + BOUNDARY);


            // 获取输出流
            DataOutputStream dos = new DataOutputStream(
                    connection.getOutputStream());
            StringBuffer sb = null;


            String result = "";
            String paramStr;
            // 发送非文件参数
            if (mParams != null && mParams.size() > 0) {


                Iterator<String> it = mParams.keySet().iterator();
                while (it.hasNext()) {
                    sb = null;
                    sb = new StringBuffer();
                    String key = it.next();
                    Object value = mParams.get(key);
                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sb.append("Content-Disposition: form-data; name=\"")
                            .append(key).append("\"").append(LINE_END)
                            .append(LINE_END);
                    sb.append(value).append(LINE_END);
                    paramStr = sb.toString();

                    dos.write(paramStr.getBytes());
                    dos.flush();
                }
            }
            paramStr = null;


            // 发送文件参数，读取文件流写入post输出流
            if (fileParams != null && !fileParams.isEmpty()) {


                Iterator<Entry<String, String>> fileIter = fileParams
                        .entrySet().iterator();


                while (fileIter.hasNext()) {
                    sb = null;
                    sb = new StringBuffer();
                    Entry<String, String> entry = fileIter.next();
                    String fileKey = entry.getKey();
                    String filePath = entry.getValue();


                    File file = new File(filePath);


                    if (file.exists() == false) {
                        throw new FileNotFoundException();
                    }
                    // 设置边界标示，设置 Content-Disposition头传入文件流
                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sb.append("Content-Disposition:form-data; name=\""
                            + fileKey + "\"; filename=\"" + file.getName()+".wma"
                            + "\"" + LINE_END);
//                    sb.append("Content-Type:" + "image/jpeg" + LINE_END);
                    sb.append("Content-Type:" + "audio/x-ms-wma" + LINE_END);
                    sb.append(LINE_END);
                    dos.write(sb.toString().getBytes());
                    InputStream is = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        dos.write(bytes, 0, len);
                    }
                    is.close();
                    dos.write(LINE_END.getBytes());
                    dos.flush();
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
            }
            dos.close();

            int res =connection.getResponseCode();
            // 返回成功
            if (res == 200) {
                InputStream input = connection.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                return result;
//                return isSuccess(result) ? imgPath : null;
            } else {
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isSuccess(Object object){

        boolean isSuccess = false;
        try{

            if(object != null){
                JSONObject json = new JSONObject(object.toString());
                if(json.has("status") && json.get("status").equals("ok")){
                    isSuccess = true;
                }else{
                    isSuccess = false;
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return isSuccess;
    }
}
